package org.zhouhe.modules.user.action;

import java.io.IOException;
import java.io.StringWriter;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.zhouhe.base.BaseAction;
import org.zhouhe.modules.user.service.UserService;
import org.zhouhe.page.PageUtil;
import org.zhouhe.util.Constant;
import org.zhouhe.vo.Menu;
import org.zhouhe.vo.Role;
import org.zhouhe.vo.User;

@SuppressWarnings("serial")
public class UserAction extends BaseAction {
	private List<Role> roleList;
	private List<Menu> menuList;
	private Integer[] roleId;
	private Integer[] menuId;
	private PageUtil pageUtil = new PageUtil();
	private User user;
	private Role role;
	private String menuTreeXmlStr;
	private List<Menu> leftMenus;
	@Autowired
	private UserService userService;

	public String test() {
		User user = new User();
		this.setPageUtil(userService.findUserByPage(pageUtil, user));
		return "success";
	}

	public String userDetail() {
		this.user = userService.getUserDetail(user.getUserId());
		return "userDetail";
	}

	public String updatePasswordDo(){
		userService.updatePassword(user.getUserId(), user.getLoginPwd());
		operationStatus = 1;
		return super.RESULT_OUTPUT_STATUS;
	}

	public String saveUserDo() {
		user.setStatus(1);
		userService.saveUser(user);
		operationStatus = 1;
		return super.RESULT_OUTPUT_STATUS;
	}

	public String userList() {
		userService.findUserByPage(pageUtil, user);
		this.roleList = userService.getRoleList();
		return "userList";
	}

	public String deleteUserDo() {
		userService.deleteUser(user);
		return this.userList();
	}
	public String configUserAuthorityDo(){
		userService.configUserRoles(user, roleId);
		operationStatus = 1;
		return super.RESULT_OUTPUT_STATUS;
	}
	public String fnidRoleIdsByUser(){
		this.roleId = userService.findRoleIdsByUser(user.getUserId());
		return "fnidRoleIdsByUser";
	}
	
	public String manage(){
		return "manage";
	}

	public String roleList(){
		roleList = userService.getRoleList();
		menuList = userService.findAllMenus();
		Document menuDoc = DocumentHelper.createDocument();
		Element menuRoot = menuDoc.addElement("tree").addAttribute("id", "0").addAttribute("text", "根节点");
		this.renderTreeXML(menuRoot, new LinkedHashSet<Menu>(menuList));
		OutputFormat format = OutputFormat.createCompactFormat();
		format.setEncoding("UTF-8");
		StringWriter out = new StringWriter();
		XMLWriter xmlWriter = new XMLWriter(out, format);
		// 打印doc
		try {
			xmlWriter.write(menuDoc);
			xmlWriter.flush();
			menuTreeXmlStr = out.toString().trim();
			menuTreeXmlStr = menuTreeXmlStr.replace("\"", "\\\"");
			menuTreeXmlStr = menuTreeXmlStr.replace("\n", "");
			menuTreeXmlStr = menuTreeXmlStr.replace("\r", "");
		} catch (Exception e) {

		}
		// 关闭输出器的流，即是printWriter

		return "roleList";
	}
	public void renderTreeXML(Element parentElement, Set<Menu> menuSet){
		for(Menu menu:menuSet){
			Element item = parentElement.addElement("item");
			item.addAttribute("id", menu.getMenuId().toString());
			item.addAttribute("text", menu.getMenuName());
			item.addAttribute("open", "1");
			Set<Menu> subMenuSet = menu.getMenus();
			if(subMenuSet != null && subMenuSet.size()>0){
				renderTreeXML(item, subMenuSet);
			}
		}
	}
	public String saveRoleDo(){
		userService.saveRole(role);
		return super.RESULT_OUTPUT_STATUS;
	}
	public String deleteRoleDo(){
		userService.deleteRole(role);
		return super.RESULT_OUTPUT_STATUS;
	}
	public String findLeafMenuIdsByRole(){
		this.menuId = userService.findLeafMenuIdsByRole(role);
		return "findMenuIdsByRole";
	}
	public String configRoleMenuDo(){
		userService.configRoleMenus(role, getMenuId());
		return super.RESULT_OUTPUT_STATUS;
	}
	public String login(){
		if(user != null && user.getLoginName() != null){
			Map<String, ?> map = userService.login(user);
			if(map != null && map.size() > 0){
				User userDetail = (User) map.get("user");
				sessionMap.put(Constant.SESSION_KEY_USER_INFO, userDetail);
				List<Menu> menuList = userService.findMenusByUserId(userDetail.getUserId());
				sessionMap.put(Constant.SESSION_KEY_USER_MENU_LIST, menuList);
				HttpServletResponse response = ServletActionContext.getResponse();
				try {
					response.sendRedirect("manage/manage.action");
				} catch (IOException e) {
					e.printStackTrace();
				}
				return SUCCESS;
			}
		}
		return "login";
	}
	public String logout(){
		sessionMap.remove(Constant.SESSION_KEY_USER_INFO);
		sessionMap.remove(Constant.SESSION_KEY_USER_MENU_LIST);
		return SUCCESS;
	}
	public String leftMenus(){
		setLeftMenus(userService.findMenusByUserId(1));
		return "leftMenus";
	}
	/************************************************************************/
	public void setPageUtil(PageUtil pageUtil) {
		this.pageUtil = pageUtil;
	}

	public PageUtil getPageUtil() {
		return pageUtil;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public User getUser() {
		return user;
	}

	public void setRoleList(List<Role> roleList) {
		this.roleList = roleList;
	}

	public List<Role> getRoleList() {
		return roleList;
	}

	public void setRoleId(Integer[] roleId) {
		this.roleId = roleId;
	}
	public Integer[] getRoleId() {
		return roleId;
	}

	@Override
	public Integer getOperationStatus() {
		return super.getOperationStatus();
	}

	public void setRole(Role role) {
		this.role = role;
	}

	public Role getRole() {
		return role;
	}

	public void setMenuId(String menuId) {
		if(menuId != null){
			String[] ids = menuId.split(",");
			Integer[] tmp = new Integer[ids.length];
			for(int i=0; i<ids.length; i++){
				tmp[i] = new Integer(ids[i]);
			}
			this.menuId = tmp;	
		}else{
			this.menuId = new Integer[0];
		}
		
	}
	public Integer[] getMenuId() {
		return menuId;
	}

	public void setMenuList(List<Menu> menuList) {
		this.menuList = menuList;
	}

	public List<Menu> getMenuList() {
		return menuList;
	}

	public void setMenuTreeXmlStr(String menuTreeXmlStr) {
		this.menuTreeXmlStr = menuTreeXmlStr;
	}

	public String getMenuTreeXmlStr() {
		return menuTreeXmlStr;
	}

	public void setLeftMenus(List<Menu> leftMenus) {
		this.leftMenus = leftMenus;
	}

	public List<Menu> getLeftMenus() {
		return leftMenus;
	}
}
